//
//  SuggesOrComplainCell.m
//  运营管理系统
//
//  Created by 杨毅 on 17/2/21.
//  Copyright © 2017年 杨毅. All rights reserved.
//

#import "SuggesOrComplainCell.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
@interface SuggesOrComplainCell()
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@end

@implementation SuggesOrComplainCell
{
    __weak IBOutlet UIView *BackView;
    __weak IBOutlet UILabel *Title;
    __weak IBOutlet UIButton *complanyName;
    __weak IBOutlet UILabel *subtitle;
    __weak IBOutlet UILabel *ZanNumber;
    __weak IBOutlet UILabel *submitName;
    __weak IBOutlet UILabel *submitTime;
    __weak IBOutlet UIImageView *ZanImageView;
    __weak IBOutlet UIButton *supportBtn;
    __weak IBOutlet UIView *FailueView;
    NSInteger supportNumber;
    NSInteger supportState;
    NSInteger cellID;
    NSInteger state;//取消还是赞的状态 0取消 1赞
    NSInteger userID;

    
}

 
 - (AFHTTPSessionManager *)manager{
 if (!_manager) {
 _manager = [AFHTTPSessionManager manager];
 }
 return _manager;
 }
 
- (NSString *)filePath{
    NSString *documentFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filetPath = [documentFilePath stringByAppendingPathComponent:@"Log.txt"];
    return filetPath;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    BackView.layer.cornerRadius = 4;
    BackView.layer.shadowOpacity = 2.0;
    BackView.layer.shadowColor = UIColorFromRGB(0xb6b6b6).CGColor;
    BackView.layer.shadowOffset = CGSizeMake(0, 0);
    FailueView.layer.cornerRadius = 15.0;
}
- (void)fillCellWithModel:(SugAndComBeanListModel *)model WithRow:(NSInteger)index{
    state = index;

    switch (model.aspectOn) {
        case 1:
            Title.text = [NSString stringWithFormat:@"%c技术问题%c%@",'[',']',model.title];
            break;
        case 2:
            Title.text = [NSString stringWithFormat:@"%c行政问题%c%@",'[',']',model.title];
            break;
        case 3:
            Title.text = [NSString stringWithFormat:@"%c备件问题%c%@",'[',']',model.title];
            break;
        case 4:
            Title.text = [NSString stringWithFormat:@"%c体系管理问题%c%@",'[',']',model.title];
            break;
        case 5:
            Title.text = [NSString stringWithFormat:@"%c其他%c%@",'[',']',model.title];
            break;
            
        default:
            break;
    }

    [complanyName setTitle:model.branchName forState:UIControlStateNormal];
    subtitle.text = model.suggestion;

    NSString *str = [NSString stringWithFormat:@"赞%c%ld%c",'(',model.supportNum,')'];
    NSMutableAttributedString *noteStr = [[NSMutableAttributedString alloc]initWithString:str];
    NSRange redRange = NSMakeRange([[noteStr string] rangeOfString:[NSString stringWithFormat:@"%ld",model.supportNum]].location,[[noteStr string] rangeOfString:[NSString stringWithFormat:@"%ld",model.supportNum]].length);
     [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:redRange];
    [self.ZanNumber setAttributedText:noteStr];
    
    
    [supportBtn.titleLabel setAttributedText:noteStr];

    if (model.anonymity == 0) {
        submitName.text = model.smtPs;
    }else{
        submitName.text = @"迭名";
    }
    if (model.supportState == 0) {
        ZanImageView.image = [UIImage imageNamed:@"thumb_up"];
        supportBtn.selected = NO;
    }else{
        ZanImageView.image = [UIImage imageNamed:@"thumb_up_blue"];
        supportBtn.selected = YES;
    }
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate* inputDate = [inputFormatter dateFromString:model.time];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init];
    [dateformatter setLocale:[NSLocale currentLocale]];
    [dateformatter setDateFormat:@"yy/MM/dd"];
    
    submitTime.text = [dateformatter stringFromDate:inputDate];
    supportState = model.supportState;
    supportNumber = model.supportNum;
    cellID = model.ID;
    NSDictionary *userDic = [NSDictionary dictionaryWithContentsOfFile:[self filePath]];
    userID =[[userDic objectForKey:@"userid"]integerValue];

}

- (IBAction)supportBtnClick:(id)sender {
    //1 没赞过 点击+1 0 赞过 点击-1

    //    实现多选
    supportBtn.selected = !supportBtn.isSelected;
   
    if (supportState == 0) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        self.manager.requestSerializer.timeoutInterval = 15;
        [_manager POST:SupportNumUrl parameters:@{@"userId":[NSString stringWithFormat:@"%ld",userID],@"supportState":@1,@"suggestionId":[NSString stringWithFormat:@"%ld",cellID]} progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if ([dic[@"status"]integerValue] == 1) {
                
                supportNumber = supportNumber+1;
                [self.delegate sugBtnClick:sender RowData:@{@"supprotNum":[NSString stringWithFormat:@"%ld",supportNumber],@"type":@"add",@"supprotState":[NSString stringWithFormat:@"%ld",supportState],@"suggestionId":[NSString stringWithFormat:@"%ld",cellID],@"row":[NSString stringWithFormat:@"%ld",state]}];

            }else{
                [UIView animateWithDuration:2.0 animations:^{
                    FailueView.alpha = 1;
                } completion:^(BOOL finished) {
                    FailueView.alpha = 0;
                }];
            }
            [MBProgressHUD hideHUDForView:self animated:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hideHUDForView:self animated:YES];
            [UIView animateWithDuration:2.0 animations:^{
                FailueView.alpha = 1;
            } completion:^(BOOL finished) {
                FailueView.alpha = 0;
            }];
        }];

    }else{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        self.manager.requestSerializer.timeoutInterval = 15;
        [_manager POST:SupportNumUrl parameters:@{@"userId":[NSString stringWithFormat:@"%ld",userID],@"supportState":@0,@"suggestionId":[NSString stringWithFormat:@"%ld",cellID]} progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            if ([dic[@"status"]integerValue] == 1) {
                
                supportNumber = supportNumber-1;
                [self.delegate sugBtnClick:sender RowData:@{@"supprotNum":[NSString stringWithFormat:@"%ld",supportNumber],@"type":@"cut",@"supprotState":[NSString stringWithFormat:@"%ld",supportState],@"suggestionId":[NSString stringWithFormat:@"%ld",cellID],@"row":[NSString stringWithFormat:@"%ld",state]}];


            
            }else{
                [UIView animateWithDuration:2.0 animations:^{
                    FailueView.alpha = 1;
                } completion:^(BOOL finished) {
                    FailueView.alpha = 0;
                }];
            }
            [MBProgressHUD hideHUDForView:self animated:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hideHUDForView:self animated:YES];
            [UIView animateWithDuration:2.0 animations:^{
                FailueView.alpha = 1;
            } completion:^(BOOL finished) {
                FailueView.alpha = 0;
            }];
        }];

    }

}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
